package com.jar.exercise.多线程.线程之间的通信;

/**
 * 实现Runnable接口
 * 使用notify(),notifyall(),wait()
 * 操作线程通信
 * 例子：消费者和生产者
 */
public class ThreadCommunication2 {
	public static void main(String[] args) {
		Product2 product2 = new Product2();
		Thread produce2 = new Thread(new Produce2(product2));
		produce2.setName("生产者");
		Thread consumer2 = new Thread(new Consumer2(product2));
		consumer2.setName("消费者");
		produce2.start();
		consumer2.start();
	}
}

class Product2 {
	private int num;

	public synchronized void consume() {
		if (num > 0) {
			System.out.println(Thread.currentThread().getName() + "：消费了第" + num + "个产品");
			num--;
			notify();
		} else {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public synchronized void produce() {
		if (num < 20) {
			num++;
			System.out.println(Thread.currentThread().getName() + "：生产了第" + num + "个产品");
			notify();
		} else {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Consumer2 implements Runnable {
	private Product2 product2;

	public Consumer2(Product2 product2) {
		this.product2 = product2;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(100);
				product2.consume();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class Produce2 implements Runnable {
	private Product2 product2;

	public Produce2(Product2 product2) {
		this.product2 = product2;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(100);
				product2.produce();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
